package logic

import (
	"context"
	"strings"

	"mall/service/blog/model"
	"mall/service/blog/rpc/internal/svc"
	"mall/service/blog/rpc/internal/utils/errorhandler"
	"mall/service/blog/rpc/types/blog"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetAttachmentListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendGetAttachmentListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetAttachmentListLogic {
	return &BackendGetAttachmentListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// ##25.03.03## 同步七牛云
func (l *BackendGetAttachmentListLogic) BackendGetAttachmentList(in *blog.BackendAttachmentListReq) (*blog.BackendAttachmentListResp, error) {
	filter := make(map[string]map[string][]any)
	filter[model.BlogAttachmentRelationshipColumns.ObjectType] = map[string][]any{
		"equalTo": {in.ObjectType},
	}
	rel, _, err := l.svcCtx.KBEntry.GetAttachmentRelationshipList(l.ctx, model.M{
		"page":     in.Page,
		"pageSize": in.PageSize,
		"select":   []string{model.BlogAttachmentRelationshipColumns.AttachmentImageURL, model.BlogAttachmentRelationshipColumns.AttachmentID, model.BlogAttachmentRelationshipColumns.ObjectID},
	}, -1, filter)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}
	var aid []uint64
	if len(rel) > 0 {
		for _, rv := range rel {
			if len(strings.TrimSpace(rv.AttachmentImageURL)) > 0 &&
				(strings.Contains(rv.AttachmentImageURL, "https://www.scentrobe.com/proxy2/static") ||
					strings.Contains(rv.AttachmentImageURL, "https://www.scentrobe.com/proxy1/static")) {
				aid = append(aid, rv.AttachmentID)
			}
		}
	}
	return &blog.BackendAttachmentListResp{
		DiagnoseAttachmentsIds: aid,
	}, nil
}
